import { resolve } from "path";
import { defineConfig, loadEnv } from "vite";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import vue from "@vitejs/plugin-vue";
import { createHtmlPlugin } from "vite-plugin-html";
import progress from "vite-plugin-progress";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import WindiCSS from "vite-plugin-windicss";



const root = process.cwd();
function pathResolve(dir: string) {
  return resolve(root, ".", dir);
}
const getViteEnv = (mode:any, target:any) => {
  return loadEnv(mode, root)[target];
};
export default ({ mode }) => {
  const _project = getViteEnv(mode, "VITE_PROJECT");
  const htmlParams = {
    minify: true,
    pages: [
      {
        filename: _project,
        entry: `/src/packages/${_project}/main.ts`,
        template: "index.html",
        injectOptions: {
          data: {
            title: `${getViteEnv(mode, "VITE_APP_TITLE")}`,
            injectIcoLink: getViteEnv(mode, "VITE_APP_FAVICON"),
          },
        },
      },
    ],
  };

  return defineConfig({
    base: "/",
    publicDir: "public", // 默认 public
    server: {
      // 服务器端口号
      port: Number(getViteEnv(mode, "VITE_PORT")),
      // 是否自动打开浏览器
      open: true,
    },
    plugins: [
      vue(),
      vueSetupExtend(),
      WindiCSS(),
      progress(),
      createHtmlPlugin(htmlParams),
      AutoImport({
        // 自动导入vue相关函数 如 ref,reactive toRef 等
        imports: ["vue", "vue-router", "pinia"],
        dts: "src/auto-import.d.ts",
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          // 全局变量
          // additionalData: '@import "./src/assets/style/global-variables.scss";',
          // element-plus升级到v2需要改成以下写法
          additionalData: `@use "./src/styles/global-variables.scss" as *;`,
          // api:'modern-compiler',
        },
      },
    },
    resolve: {
      // alias: {
      //   "@": path.resolve(__dirname, "src"),
      // },
      alias: [
        {
          find: /\@\//,
          replacement: `${pathResolve("src")}/`,
        },
      ],
    },
    build: {
      target: "esnext",
      cssCodeSplit: true,
      emptyOutDir: true,
      sourcemap: false,
      assetsDir: "assets", // 默认 assets
      outDir: `dist/${_project}`, // 默认 dist
    },
  })
}
